package com.chenfei.config;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * @author chenfei
 * @description
 * @since 2018/3/15
 */
@Configuration
public class JestConfig {
    @Value("${spring.elasticsearch.jest.url}")
    private String connectionUrl;

    @Value("${spring.elasticsearch.jest.connection-timeout}")
    private Integer connectionTimeout;

    @Value("${spring.elasticsearch.jest.read-timeout}")
    private Integer readTimeout;

    private JestClient jestClient;

    //@Bean
    public HttpClientConfig httpClientConfig() {
        LinkedHashSet<String> servers = new LinkedHashSet<String>();
        servers.add("http://localhost:9200");
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder("http://localhost:9200").multiThreaded(true).maxTotalConnection(50);
        builder.addServer(servers);
        builder.connTimeout(connectionTimeout);
        builder.readTimeout(readTimeout);
        HttpClientConfig httpClientConfig = builder.build();
        return httpClientConfig;
    }

    @Bean
    public JestClient jestClient() {
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(httpClientConfig());
        if (jestClient == null) {
            jestClient = factory.getObject();
        }
        return jestClient;
    }
}
